package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/2 0002 上午 9:17
 */

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        //1、查询访客数据
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        //2、不存在，保存
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> queryMyVisitors(Long date, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (date != null) {
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query, Visitors.class);
    }

    @Override
    public PageResult myVisitors(Integer page, Integer pagesize, Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Visitors.class);

        query.skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);

        return new PageResult(page,pagesize,count,visitors);
    }
}
